<!--
  * 工单BOM详情
  *
  * @Author:    lmabbe
  * @Date:      2025-07-03 17:39:42
  * @Copyright  lmabbe
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form" size="small">
    <a-row class="smart-query-form-row">
      <a-form-item class="smart-query-form-item" label="关键词查询">
        <a-input v-model:value="queryForm.keywords" placeholder="可查询物料编号/名称/规格" style="width: 200px" />
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="位置查询">
        <a-input v-model:value="queryForm.location" placeholder="位置查询" style="width: 200px" />
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="物料类型">
        <SmartEnumSelect v-model:value="queryForm.materialType" enum-name="PRODUCT_BOM_DETAIL_MATERIAL_TYPE_ENUM" size="small" style="width: 200px" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button class="smart-margin-left10" @click="resetQuery">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <!---------- 表格操作行 begin ----------->
  <a-row class="smart-table-btn-block">
    <div class="smart-table-operate-block">
      <a-button v-privilege="'workOrderBomDetail:syncBom'" size="small" type="primary" @click="confirmSyncBom">
        <template #icon>
          <PlusOutlined />
        </template>
        同步BOM
      </a-button>
      <a-button v-privilege="'workOrderBomDetail:reCalcDosage'" size="small" type="primary" @click="reCalcDosage(true)">
        <template #icon>
          <ReloadOutlined />
        </template>
        重新计算用量
      </a-button>
    </div>
  </a-row>
  <!---------- 表格操作行 end ----------->

  <!---------- 表格 begin ----------->
  <a-table
    :columns="columns"
    :dataSource="tableData"
    :loading="tableLoading"
    :pagination="false"
    :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
    :scroll="{ y: 360 }"
    bordered
    rowKey="bomId"
    size="small"
  >
    <template #bodyCell="{ text, record, column }">
      <template v-if="column.dataIndex === 'materialType'">
        <span>{{ $smartEnumPlugin.getDescByValue('PRODUCT_BOM_DETAIL_MATERIAL_TYPE_ENUM', text) }}</span>
      </template>

      <template v-if="column.dataIndex === 'action'">
        <div class="smart-table-operate">
          <a-button v-privilege="'workOrderBomDetail:update'" type="link" @click="showForm(record)">编辑</a-button>
          <a-button v-privilege="'workOrderBomDetail:delete'" danger type="link" @click="onDelete(record)">删除 </a-button>
        </div>
      </template>
    </template>
  </a-table>
  <!---------- 表格 end ----------->

  <div class="smart-query-table-page">
    <a-pagination
      v-model:current="queryForm.pageNum"
      v-model:pageSize="queryForm.pageSize"
      :defaultPageSize="queryForm.pageSize"
      :pageSizeOptions="PAGE_SIZE_OPTIONS"
      :show-total="(total) => `共${total}条`"
      :total="total"
      show-less-items
      showQuickJumper
      showSizeChanger
      size="small"
      @change="queryData"
      @showSizeChange="queryData"
    />
  </div>

  <WorkOrderBomDetailForm ref="formRef" @reloadList="queryData" />
</template>
<script setup>
  import { reactive, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import { workOrderBomDetailApi } from '/@/api/business/product/order/work-order-bom-detail-api.js';
  import { smartSentry } from '/@/lib/smart-sentry';
  import WorkOrderBomDetailForm from './work-order-bom-detail-form.vue';
  import { PRODUCT_BOM_DETAIL_MATERIAL_TYPE_ENUM } from '/@/constants/business/product/bom/bom-detail-const.js';
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue';

  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: '物料类型',
      dataIndex: 'materialType',
      ellipsis: true,
    },
    {
      title: '物料编码',
      dataIndex: 'materialCode',
      ellipsis: true,
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      ellipsis: true,
    },
    {
      title: '物料规格',
      dataIndex: 'materialSpec',
      ellipsis: true,
    },
    {
      title: '物料描述',
      dataIndex: 'materialDesc',
      ellipsis: true,
    },
    {
      title: '主料物料编码',
      dataIndex: 'mainMaterialCode',
      ellipsis: true,
    },
    {
      title: '物料单位',
      dataIndex: 'materialUnit',
      ellipsis: true,
    },
    {
      title: '用量',
      dataIndex: 'dosage',
      ellipsis: true,
    },
    {
      title: 'T面位置',
      dataIndex: 'locationT',
      ellipsis: true,
    },
    {
      title: 'B面位置',
      dataIndex: 'locationB',
      ellipsis: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
    },
    {
      title: '工单需求量',
      dataIndex: 'demandQty',
      ellipsis: true,
    },
    {
      title: '实际发放量',
      dataIndex: 'actualProvideQty',
      ellipsis: true,
    },
    {
      title: '实际使用量',
      dataIndex: 'actualUseQty',
      ellipsis: true,
    },
    {
      title: '损耗率',
      dataIndex: 'lossRate',
      ellipsis: true,
    },
    {
      title: '禁用状态',
      dataIndex: 'disabledFlag',
      ellipsis: true,
    },
    {
      title: '创建人',
      dataIndex: 'updateUserName',
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      ellipsis: true,
    },
    {
      title: '更新人',
      dataIndex: 'updateUserName',
      ellipsis: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      ellipsis: true,
    },
  ]);

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    keywords: undefined, //关键词查询
    workOrderId: undefined, //工单ID
    location: undefined, //位置查询
    materialType: undefined, //物料类型:[1:主料，2:替代料]
    pageNum: 1,
    pageSize: 10,
  };
  // 查询表单form
  const queryForm = reactive({ ...queryFormState });
  // 表格加载loading
  const tableLoading = ref(false);
  // 表格数据
  const tableData = ref([]);
  // 总数
  const total = ref(0);

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize;
    Object.assign(queryForm, queryFormState);
    queryForm.pageSize = pageSize;
    queryData();
  }

  // 搜索
  function onSearch() {
    queryForm.pageNum = 1;
    queryData();
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true;
    try {
      let queryResult = await workOrderBomDetailApi.queryPage(queryForm);
      tableData.value = queryResult.data.list;
      total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }

  // ---------------------------- 添加/修改 ----------------------------
  const formRef = ref();

  function showForm(data) {
    formRef.value.show(data);
  }

  // ---------------------------- 单个删除 ----------------------------
  //确认删除
  function onDelete(data) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除选吗?',
      okText: '删除',
      okType: 'danger',
      onOk() {
        requestDelete(data);
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  //请求删除
  async function requestDelete(data) {
    SmartLoading.show();
    try {
      let deleteForm = {
        goodsIdList: selectedRowKeyList.value,
      };
      await workOrderBomDetailApi.delete(data.bomId);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // ---------------------------- 批量删除 ----------------------------

  // 选择表格行
  const selectedRowKeyList = ref([]);

  function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys;
  }

  function confirmSyncBom() {
    Modal.confirm({
      title: '提示',
      content: '确定要重新同步吗?重新同步会删除旧的数据！',
      okText: '同步',
      okType: 'danger',
      onOk() {
        requestSyncBom();
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  async function requestSyncBom() {
    workOrderBomDetailApi.syncBom(orderInfoRef.value.workOrderId).then((res) => {
      reCalcDosage(false);
      message.success('同步成功');
      queryData();
    });
  }

  function reCalcDosage(showMsg) {
    workOrderBomDetailApi.reCalcDosage(orderInfoRef.value.workOrderId).then((res) => {
      if (showMsg) {
        message.success('重新计算成功');
        queryData();
      }
    });
  }

  const orderInfoRef = ref();

  function setOrderInfo(val) {
    orderInfoRef.value = val;
    queryForm.workOrderId = val.workOrderId;
    queryData();
  }

  defineExpose({
    setOrderInfo,
  });
</script>
